package com.atguigu.spzx.service.impl;

import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.mapper.SysRoleMapper;
import com.atguigu.spzx.mapper.SysUserMapper;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.service.SysRoleService;
import com.atguigu.spzx.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public LoginVo login(LoginDto loginDto) {
        // 获取验证码 获取验证码的key
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        //获取redis中的验证码
        String redisCaptcha = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        // 判断验证码
        if (StringUtils.isEmpty(redisCaptcha) || !StringUtils.equalsAnyIgnoreCase(captcha,redisCaptcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //验证码相同,删除redis
        redisTemplate.delete("user:login:validatecode:"+codeKey);


        //1,获取提交的用户名称
        String userName = loginDto.getUserName();
        //2,查询用户信息
        SysUser sysUser = sysUserMapper.selectUserByName(userName);
        //3,如果用户不存在,返回错误信息
        if (null == sysUser) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //4,如果用户存在
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //5,获取输入密码,和数据库密码进行比较
        //6,如果密码正确,登陆成功
        if (!input_password.equals(sysUser.getPassword())) {
            //7,如果密码不一致,登陆失败

            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //8,登陆成功,生成token,返回token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //9,保存进入redis,设置过期时间
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        // 获取用户信息
        return JSON.parseObject(redisTemplate.opsForValue().get("user:login" + token),SysUser.class);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum , pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto) ;
        PageInfo pageInfo = new PageInfo(sysUserList) ;
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.findByUserName(sysUser.getUserName()) ;
        if(dbSysUser != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS) ;
        }

        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.saveSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser) ;
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId) ;
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {

        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.dodoAssign(assginRoleDto.getUserId(),roleId);
        });


    }


}
